//
//  ToneSelectViewController.swift
//  Duyiguqin
//
//  Created by 张昭 on 2024/8/10.
//

import UIKit

class ToneSelectViewController: UIViewController {
    
    var onSubmit: ((Tone) -> Void)?
    
    private let defaultSelectedTone: Tone
    
    init(tone v: Tone) {
        defaultSelectedTone = v
        super.init(nibName: nil, bundle: nil)
        self.transitioningDelegate = self
        self.modalPresentationStyle = .overFullScreen
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        addContentView()
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touchPoint = touches.first?.location(in: view) else { return }
        guard !boardView.frame.contains(touchPoint) else { return }
        dismiss(animated: true)
    }
    
    override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        contentView.snp.updateConstraints { make in
            make.bottom.equalTo(-view.safeAreaInsets.bottom)
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if boardView.layer.mask == nil {
            boardView.roundCorners(corners: [.topLeft, .topRight], radius: 5)
        }
    }
    
    lazy var contentView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.white
        return v
    }()
    
    private lazy var boardView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.white
        return v
    }()
    
    private lazy var tableView: UITableView = {
        let v = UITableView(frame: .zero, style: .plain)
        v.register(Cell.self, forCellReuseIdentifier: "reuse")
        v.delegate = self
        v.dataSource = self
        return v
    }()
    
    private lazy var cancelButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setTitle("取消", for: .normal)
        v.setTitleColor(UIColor.black, for: .normal)
        v.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: .regular)
        v.addTarget(self, action: #selector(onClickCloseButton(_:)), for: .touchUpInside)
        return v
    }()
    
    private lazy var okButton: UIButton = {
        let v = UIButton(type: .custom)
        v.setTitle("确定", for: .normal)
        v.setTitleColor(UIColor(0xD3C390), for: .normal)
        v.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: .regular)
        v.addTarget(self, action: #selector(onClickOKButton(_:)), for: .touchUpInside)
        return v
    }()
    
    private let items: [Tone] = [.F, .bB, .C, .G, .bE, .D]
    private var selectedItem: Tone?
}

extension ToneSelectViewController {
    
    private func addContentView() {
        view.backgroundColor = .clear
        view.addSubview(boardView)
        boardView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
        }
        
        boardView.addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.top.left.right.equalTo(0)
            make.bottom.equalTo(-view.safeAreaInsets.bottom)
        }
        
        contentView.addSubview(cancelButton)
        cancelButton.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.height.equalTo(40)
            make.top.equalTo(10)
        }
        
        contentView.addSubview(okButton)
        okButton.snp.makeConstraints { make in
            make.right.equalTo(-15)
            make.height.equalTo(40)
            make.centerY.equalTo(cancelButton)
        }
        
        contentView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.height.equalTo(CGFloat(items.count) * 64)
            make.left.right.bottom.equalTo(0)
            make.top.equalTo(cancelButton.snp.bottom).offset(10)
        }
        
        if let idx = items.firstIndex(where: { $0 == defaultSelectedTone }) {
            tableView.selectRow(at: IndexPath(row: idx, section: 0), animated: false, scrollPosition: .none)
        }
    }
    
    @objc func onClickCloseButton(_ sender: UIButton) {
        view.endEditing(true)
        dismiss(animated: true, completion: nil)
    }
    
    @objc func onClickOKButton(_ sender: UIButton) {
        view.endEditing(true)
        dismiss(animated: true) { [weak self] in
            if let tone = self?.selectedItem {
                self?.onSubmit?(tone)
            }
        }
    }
}

extension ToneSelectViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell: Cell = tableView.dequeueReusableCell(withIdentifier: "reuse", for: indexPath) as? Cell {
            let item = items[indexPath.row]
            cell.update(item.title, desc: item.desc)
            return cell
        }
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let item = items[indexPath.row]
        selectedItem = item
    }
}

// MARK: - UIViewControllerTransitioningDelegate
extension ToneSelectViewController: UIViewControllerTransitioningDelegate {
    
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return self
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return self
    }
}

// MARK: - UIViewControllerAnimatedTransitioning
extension ToneSelectViewController: UIViewControllerAnimatedTransitioning {
    
    private var transitionDuration: TimeInterval {
        return 0.15
    }
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return transitionDuration
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        if isBeingPresented {
            transitionContext.containerView.addSubview(view)
            boardView.transform = CGAffineTransform(translationX: 0, y: 300)
            self.view.backgroundColor = UIColor(0x35373F, alpha: 0)
            UIView.animate(withDuration: transitionDuration) {
                self.boardView.transform = CGAffineTransform.identity
                self.view.backgroundColor = UIColor(0x35373F, alpha: 0.8)
            } completion: { _ in
                transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            }
        } else {
            UIView.animate(withDuration: transitionDuration) {
                self.boardView.transform = CGAffineTransform(translationX: 0, y: self.boardView.frame.size.height)
                self.view.backgroundColor = UIColor(0x35373F, alpha: 0)
            } completion: { _ in
                transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            }
        }
    }
}

fileprivate class Cell: UITableViewCell {
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        initializeSubviews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var tLabel: UILabel = {
        let v = UILabel()
        v.textColor = UIColor(0x0F0F0F)
        v.font = UIFont.systemFont(ofSize: 18, weight: .medium)
        return v
    }()
    
    private lazy var descLabel: UILabel = {
        let v = UILabel()
        v.textColor = UIColor(0x0F0F0F)
        v.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        return v
    }()
    
    private func initializeSubviews() {
        
        contentView.addSubview(tLabel)
        tLabel.snp.makeConstraints { make in
            make.top.equalTo(10)
            make.left.equalTo(15)
            make.right.lessThanOrEqualToSuperview().offset(-10)
        }
        
        contentView.addSubview(descLabel)
        descLabel.snp.makeConstraints { make in
            make.top.equalTo(tLabel.snp.bottom).offset(5)
            make.bottom.equalTo(-10)
            make.left.equalTo(tLabel)
        }
    }
    
    func update(_ title: String, desc: String) {
        tLabel.text = title
        descLabel.text = desc
    }
}
